package com.ybkj.daijia.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.AreaWeight;
import com.ybkj.daijia.server.model.ChargeStartTime;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.service.AreaService;
import com.ybkj.daijia.server.service.ChargeStartTimeService;
import com.ybkj.daijia.server.service.CompanyService;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "area")
public class AreaController {

    @Autowired
    private AreaService areaService;
    @Autowired
    private ChargeStartTimeService chargeStartTimeService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isPermitted("area")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("area/list");
            Principal principal = (Principal) subject.getPrincipal();
            List<Company> companyList = new ArrayList<>();
            List<Area> areaList;
            if (principal.isCompanyType()) {
                areaList = areaService.listAllByCompanyId(null, null);
                companyList = companyService.findAll();
            } else {
                areaList = areaService.listAllByCompanyId(null, principal.getCompanyId());
                Company company = companyService.findOne(principal.getCompanyId());
                companyList.add(company);
            }
            if (CollectionUtils.isNotEmpty(areaList)) {
                for (Area area : areaList) {
                    area.sortDistance();
                    area.sortWeight();
                }
            }
            mv.addObject("companys", companyList);
            mv.addObject("arealist", areaList);
            return mv;
        } else {
            throw new NoPermissionException();
        }
    }


    @RequestMapping("queryCompanys")
    @ResponseBody
    public String queryCompanys() {
        Subject subject = SecurityUtils.getSubject();
        List<Company> companyList = new ArrayList<>();
        List<Company> sortList = new ArrayList<>();
        if (subject.isPermitted("area")) {
            Principal principal = (Principal) subject.getPrincipal();
            sortList.add(companyService.findOne(principal.getCompanyId()));
            if (principal.isCompanyType()) {
                companyList = companyService.findAll();
            }
            for (Company c : companyList) {
                if (c.getId() != principal.getCompanyId()) {
                    sortList.add(c);
                }
            }
        }
        JSONObject json = new JSONObject();
        json.put("data", sortList);
        String result = JSONObject.toJSONString(json);
        return result;
    }

    @RequestMapping(value = "weightlist", method = RequestMethod.GET)
    public ModelAndView weightlist() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("area")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("area/weightlist");

            List<AreaWeight> arealist = areaService.listAllWeight();

            if (CollectionUtils.isNotEmpty(arealist)) {
                for (AreaWeight area : arealist) {

                    area.sortDistance();
                }
            }

            mv.addObject("weightarealist", arealist);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 模糊查询收费标准.
     */
    @RequestMapping(value = "listData", method = RequestMethod.GET)
    public @ResponseBody
    List<Area> listData(@RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "companyId", required = false) Long companyId) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("area")) {
            List<Area> arealist = areaService.listByName(name, companyId);

            if (CollectionUtils.isNotEmpty(arealist)) {
                for (Area area : arealist) {
                    area.sortDistance();
                }
            }
            return arealist;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 模糊查询重量收费标准.
     */
    @RequestMapping(value = "listWeightData", method = RequestMethod.GET)
    public @ResponseBody
    List<AreaWeight> listWeightData(String name) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("area")) {
            List<AreaWeight> arealist = areaService.listWeightData(name);

            if (CollectionUtils.isNotEmpty(arealist)) {
                for (AreaWeight area : arealist) {
                    area.sortDistance();
                }
            }
            return arealist;
        } else {
            throw new NoPermissionException();
        }

    }

    /**
     * 根据名称模糊查询收费标准.
     */
    @RequestMapping(value = "queryByName", method = RequestMethod.GET)
    public @ResponseBody
    List<Area> queryByName(String keyword) {
        return areaService.queryByName(keyword);
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Result<Area> create(Model model, Area area, @RequestParam("companyId") Long companyId) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Area> result = new Result<Area>();

        if (subject.isPermitted("area")) {
            if (nameExists(area.getName(), null)) {
                result.setSuccess(false);
                result.setMessage("地区名称'" + area.getName() + "'已存在！");
                return result;
            }
            area.setCompanyId(companyId);
            areaService.save(area);

            String detail = "【%s】新增了地区收费【" + area.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);
            result.setMessage("保存成功！");
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

        return result;
    }

    @RequestMapping(value = "createWeight", method = RequestMethod.POST)
    public @ResponseBody
    Result<AreaWeight> createWeight(Model model, AreaWeight area) {
        try {
            Subject subject = SecurityUtils.getSubject();
            Principal principal = (Principal) subject.getPrincipal();

            Result<AreaWeight> result = new Result<AreaWeight>();

            if (subject.isPermitted("area")) {
                if (weightNameExists(area.getName(), null)) {
                    result.setSuccess(false);
                    result.setMessage("地区名称'" + area.getName() + "'已存在！");
                    return result;
                }

                areaService.saveWeight(area);

                String detail = "【%s】新增了重量收费【" + area.getName() + "】";
                OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                applicationEventMulticaster.multicastEvent(operationLogEvent);

                result.setSuccess(true);
                result.setMessage("保存成功！");
            } else {
                result.setSuccess(false);
                result.setMessage("您没有该权限");
                return result;
            }

            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping(value = "save", method = RequestMethod.POST)
    public @ResponseBody
    Result<Area> save(Model model, Area area) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Area> result = new Result<Area>();

        if (subject.isPermitted("area")) {
            if (nameExists(area.getName(), area.getId())) {
                result.setSuccess(false);
                result.setMessage("地区名称'" + area.getName() + "'已存在！");
                return result;
            }

            String detail = "【%s】修改了地区收费【" + area.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            areaService.update(area);

            result.setSuccess(true);
            result.setMessage("保存成功！");
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

        return result;

    }

    @RequestMapping(value = "saveWeight", method = RequestMethod.POST)
    public @ResponseBody
    Result<AreaWeight> saveWeight(Model model, AreaWeight area) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<AreaWeight> result = new Result<AreaWeight>();

        if (subject.isPermitted("area")) {
            if (weightNameExists(area.getName(), area.getId())) {
                result.setSuccess(false);
                result.setMessage("重量收费标准名称'" + area.getName() + "'已存在！");
                return result;
            }

            String detail = "【%s】修改了重量收费【" + area.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            areaService.updateWeight(area);

            result.setSuccess(true);
            result.setMessage("保存成功！");
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }

        return result;

    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> delete(Long id, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("area")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                Area area = areaService.findOne(id);
                if (null != area) {

                    if (!CollectionUtils.isEmpty(companyService.findByArea(area.getId()))) {
                        result.setMessage("'" + area.getName() + "'被公司引用，不能删除");
                        return result;
                    }

                    String detail = "【%s】删除了地区收费【" + area.getName() + "】";

                    areaService.delete(area);

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    result.setSuccess(true);
                    result.setMessage("删除成功");
                } else {
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "deleteWeight", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> deleteWeight(Long id, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("area")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                AreaWeight area = areaService.findOneWeight(id);
                if (null != area) {

                    // if(!CollectionUtils.isEmpty(companyService.findByAreaWeight(area.getId()))){
                    // result.setMessage("'"+area.getName()+"'被公司引用，不能删除");
                    // return result;
                    // }

                    String detail = "【%s】删除了重量收费【" + area.getName() + "】";

                    areaService.deleteWeight(area);

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    result.setSuccess(true);
                    result.setMessage("删除成功");
                } else {
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "deleteitem", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> deleteitem(Long id, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("area")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                ChargeStartTime cst = chargeStartTimeService.findOne(id);
                if (null != cst) {
                    chargeStartTimeService.delete(cst);

                    result.setSuccess(true);
                    result.setMessage("删除成功");
                } else {
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    private boolean nameExists(String name, Long id) {
        Area area = areaService.findByName(name);
        if (null != area) {
            if (null != id && id.equals(area.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    private boolean weightNameExists(String name, Long id) {
        List<AreaWeight> area = areaService.listWeightData(name);
        if (null != area && area.size() > 0) {
            for (int i = 0; i < area.size(); i++) {
                if (null != id && id.equals(area.get(i).getId())) {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}
